package com.mscsoft.tools;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/** 与服务器通讯工具类 */
public class ConTools {
    private static int uid = -1;// 当前登录的uid

    public static int getUid() {
        return uid;
    }

    public static void setUid(int uid) {
        ConTools.uid = uid;
    }

    public static void updateScore(int msid, int score, int combo, boolean ap, boolean fc) {
        String[] args = new String[] { "uid=" + uid, "msid=" + msid,
                "score=" + score, "combo=" + combo, "ap=" + ap, "fc=" + fc };
        MyHTTP.get("http://" + MyHTTP.serverAddr + "/game/updateScore", args);
    }

    public static GameScore getBestScore(int msid) {
        String[] args = new String[] { "uid=" + uid, "msid=" + msid };
        Msg<GameScore> msg = MyHTTP.<GameScore>get("http://" + MyHTTP.serverAddr + "/game/getBestScore", args,
                GameScore.class);
        return msg.getData();
    }

    public static ScoreRank[] getScoreRank(int msid) {
        String[] args = new String[] { "uid=" + uid, "msid=" + msid };
        Msg<ScoreRank[]> msg = MyHTTP.<ScoreRank[]>get("http://" + MyHTTP.serverAddr + "/game/getScoreRank", args,
                ScoreRank[].class);
        return msg.getData();
    }

    public static GameFile downloadmsc(String msc) {
        String[] args = new String[] { "name=" + msc };
        Msg<GameFile> msg = MyHTTP.<GameFile>get("http://" + MyHTTP.serverAddr + "/download/msc", args,
                GameFile.class);
        return msg.getData();
    }

    public static String sha1(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] bytes = md.digest(str.getBytes(StandardCharsets.UTF_8));
            StringBuilder ret = new StringBuilder(bytes.length << 1);
            char[] hexDigits = "0123456789abcdef".toCharArray();
            for (int i = 0; i < bytes.length; i++) {
                ret.append(hexDigits[(bytes[i] >> 4) & 0x0f]);
                ret.append(hexDigits[bytes[i] & 0x0f]);
            }
            return ret.toString();
        } catch (Exception e) {
            return null;
        }
    }

    private ConTools() {
        throw new IllegalStateException("Utility class");
    }

}
